package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand>implements BrandService {
   @Autowired
    private CategoryBrandService categoryBrandService;
    @Override
    public PageDTO<com.leyou.item.dto.BrandDTO> pageQuery(Integer page, Integer rows, String key) {
        Page<Brand>pageObj=new Page<>(page,rows);
        //判断key是否为空。不为空则为true  为空则为false
        boolean condi= StringUtils.isNotBlank(key);
        //子查询条件中加Boolean判断，条件为true  查询才生效 动态sql
        Page<Brand>brandPage=page(pageObj,
                new QueryWrapper<Brand>().like(condi,"name",key)
                 .or()
                .eq(condi,"letter",key));
        //封装分页返回的结果PageDTO
        return new PageDTO<>(brandPage.getTotal(),brandPage.getPages(), com.leyou.item.dto.BrandDTO.convertEntityList(brandPage.getRecords()));
    }

    @Override
    @Transactional  //涉及到多张表的业务  多个事务（save、saveBrand） 加上@Transactional 相当于一个事务
    public void saveBrand(BrandDTO brandDTO) {
        //保存品牌 主键回显
        Brand brand=brandDTO.toEntity(Brand.class);
        save(brand);
        //获取分类ID集合
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
    }

    private void saveCategoryBrand(List<Long>categoryIds, Long bid) {


        List<CategoryBrand>categoryBrands=
                categoryIds
                .stream()
                .map(
                        cid->
                                CategoryBrand.of(cid,bid)
                ).collect(Collectors.toList());
        //保存中间表   批量保存
        categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long cid) {
        //在中间表根据分类的id查询品牌id的集合
        List<Long>brandIds=this.categoryBrandService.query()
                .eq("category_id",cid)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        //根据品牌id的集合查询对应的品牌集合并转换为DTO
        return BrandDTO.convertEntityList(listByIds(brandIds));
    }

    @Override
    public void deleteBrandById(Long id) {
        //TODO ：要删除品牌必须先检查品牌是否有用  如果有用  拒绝删除
//品牌删除成功后  删除中间表
        if (removeById(id)){
            //关于中间表的删除
            deleteCategoryBrandByBrandId(id);
        }

    }

    private void deleteCategoryBrandByBrandId(Long id) {
        this.categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id",id)
        );
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {

        Brand brand=brandDTO.toEntity(Brand.class);

        //修改品牌
        if (updateById(brand)){
//修改中间表
            //删除品牌分类的中间关系   然后重建
            deleteCategoryBrandByBrandId(brand.getId());
   //重建品牌及分类之间的的关系
            saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());
        }

    }

}
